Dashboard Temp Share Shortlinks Frames API

HTMLify

380. Insert Delete GetRandom O(1).java
Views: 1 | Author: cody
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// 380. Insert Delete GetRandom O(1)
class RandomizedSet {
    HashMap<Integer, Integer> hm;
    List<Integer> list;
    Random r;
    public RandomizedSet() {
        hm = new HashMap<>();
        list = new ArrayList<>();
        r = new Random();
    }

    public boolean insert(int val) {
        if (hm.containsKey(val)) {
            return false;
        }else{
            hm.put(val, list.size());
            list.add(val);
            return true;
        }
    }

    public boolean remove(int val) {
        if (hm.containsKey(val) == false) {
            return false;
        }

        int idx = hm.get(val);
          hm.remove(val);
        if (idx == list.size()-1) {
            list.remove(list.size()-1);
            return true;
        }
        int idx2 = list.size()-1;
        int temp = list.get(idx2);
        swap(idx,idx2);
        list.remove(list.size()-1);
        
        hm.put(temp,idx);
        return true;
    }

    public int getRandom() {
        int idx = r.nextInt(list.size());
        return list.get(idx);
    }
    public void swap(int i,int j){
        int a = list.get(i);
        int b = list.get(j);
        list.set(i,b);
        list.set(j,a);
    }
}